const { orderApi } = require('../../utils/api/index.js')
// pages/order/index.js
Page({

  /**
   * 页面的初始数据
   */
  data: {
    activeTab: 'current', // 当前选中的标签：current-当前订单，history-历史订单
    currentOrders: [], // 当前订单列表
    historyOrders: [], // 历史订单列表
    pageSize: 20,
    currentPageNum: 1,
    hisPageNum: 1,
    optType: "new" //操作类型，如果是滚动下滑，数据需要加上之前页查询的部分，否则覆盖
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad() {
    //this.loadOrders();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({
      optType: "new"
    });
    this.loadOrders();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    if("current" === tab){
      var pageNum = this.data.currentPageNum;
      this.setData({
        currentPageNum: pageNum + 1
      });
    }else if("history" === tab){
      var pageNum = this.data.currentPageNum;
      this.setData({
        currentPageNum: pageNum + 1
      });
    }
    this.setData({
      optType: "append"
    });
    this.loadOrders();
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 切换订单类型标签
  switchTab(e) {
    const tab = e.currentTarget.dataset.tab;
    if("current" === tab){
      this.setData({
        hisPageNum: 1
      });
    }else if("history" === tab){
      this.setData({
        currentPageNum: 1
      });
    }
    this.setData({
      activeTab: tab,
      optType: "new"
    });
    this.loadOrders({ optType: "new"});
  },

  // 加载订单数据
  async loadOrders() {
    var optType  = this.data.optType;
    // 根据activeTab判断查询当前订单还是历史订单
    var activeTab = this.data.activeTab;
    var param = {}; //TODO 这里先写死userId,后续从token中拿
    if("current" === activeTab){
      //未完成的订单
      param = {
        dataType: 'unDone',
        userId: '1837425962481504256',
        pageNum: this.data.currentPageNum,
        pageSize: this.data.pageSize
      }
    }else if("history" === activeTab){
      //历史订单
      param = {
        dataType: 'done',
        userId: '1837425962481504256',
        pageNum: this.data.hisPageNum,
        pageSize: this.data.pageSize
      }
    }
    //查询订单
    try {
      const result = await orderApi.queryOrderList(param);
      if (result.code === '0000') {
        if("current" === activeTab){
          if(optType == "new"){
            //覆盖
            this.setData({
              currentOrders: result.data.list
            });
          }else{
            //追加
              var currentOrders = this.data.currentOrders;
              result.data.list.forEach(item => {
                currentOrders.push(item);
              });
              this.setData({
                currentOrders: currentOrders
              });
          }
          
        }else if("history" === activeTab){
          if(optType == "new"){
            //覆盖
            this.setData({
              historyOrders: result.data.list
            });
          }else{
            //追加
            var historyOrders = this.data.historyOrders;
              result.data.list.forEach(item => {
                historyOrders.push(item);
              });
              this.setData({
                historyOrders: historyOrders
              });
          }
          
        }
      }else{
        wx.showToast({
          title: '获取订单失败：'+ result.msg,
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('获取订单失败：', error)
      wx.showToast({
        title: '获取订单失败',
        icon: 'none'
      })
    }
  },

  // 取消订单
  cancelOrder(e) {
    const { id } = e.currentTarget.dataset;
    wx.showModal({
      title: '提示',
      content: '确定要取消该订单吗？',
      success: (res) => {
        if (res.confirm) {
          this.updateOrderStatus(id);
        }
      }
    });
  },

  async updateOrderStatus(orderId){
    // 这里应该调用取消订单的接口
    try {
      var param = {
        orderId: orderId,
        status: "cancelled"
      }
      const result = await orderApi.updateOrderStatus(param);
      if (result.code === '0000') {
        wx.showToast({
          title: '订单已取消',
          icon: 'success'
        });
        this.setData({
          optType: "new"
        })
        this.loadOrders();
      }else{
        wx.showToast({
          title: '订单取消失败'+ result.msg,
          icon: 'none'
        })
      }
    } catch (error) {
      console.error('订单取消失败：', error)
      wx.showToast({
        title: '订单取消失败',
        icon: 'none'
      })
    }
  },


  // 支付订单
  payOrder(e) {
    const { id } = e.currentTarget.dataset;
    
    // 这里应该调用支付接口
    wx.showToast({
      title: '支付功能开发中',
      icon: 'none'
    });
  },

  // 删除订单
  deleteOrder(e) {
    const { id } = e.currentTarget.dataset;
    wx.showModal({
      title: '提示',
      content: '确定要删除该订单吗？',
      success: (res) => {
        if (res.confirm) {
          // 这里应该调用删除订单的接口
          wx.showToast({
            title: '订单已删除',
            icon: 'success'
          });
          this.loadOrders();
        }
      }
    });
  }
})